
int save_rgb_as_ppm(unsigned char* buffer, int linesize, int width, int height, const char* outfile)
{
	int ret = 0;
	FILE *pFile = NULL;
	pFile = fopen(outfile, "wb");
	if( !pFile ) {
		fprintf(stderr, "open file(%s) to write error(reason:%s), save_rgb_as_ppm failed\n", outfile, strerror(errno));
		ret = -1;
		goto out;
	}
	if (fprintf(pFile, "P6\n%d %d\n255\n", width, height) < 0) {
		fprintf(stderr, "fprintf to file(%s) error(reason:%s), save_rgb_as_ppm failed\n", outfile, strerror(errno));
		ret = -1;
		goto out;
	}

	int y = 0;
	for( y = 0; y < height; y++ ) {
		//in some suituation, linesize is not equal to width*3(eg:the buffer is consturct by ffmpeg avframe)
		if (fwrite(buffer + y * linesize, 1, width * 3, pFile) != width * 3) {
			fprintf(stderr, "fwrite to file(%s) error(reason:%s), save_rgb_as_ppm failed\n", outfile, strerror(errno));
			ret = -1;
			goto out;
		}
	}
out:
	if (pFile)
		fclose(pFile);
	return ret;
}
